package com.ali.item.service.impl;

import com.ali.item.common.DecreaseStockInput;
import com.ali.item.entity.ItemInfo;
import com.ali.item.entity.ItemSku;
import com.ali.item.enums.ResultEnum;
import com.ali.item.exception.ItemException;
import com.ali.item.repository.ItemInfoRepository;
import com.ali.item.repository.ItemSkuRepository;
import com.ali.item.service.ItemSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @Description
 * @Author Alistair.Chow
 * @date 2019/1/28 17:28
 */
@Service
public class ItemSkuServiceImpl implements ItemSkuService {
    @Autowired
    private ItemSkuRepository itemSkuRepository;
    @Autowired
    private ItemInfoRepository itemInfoRepository;

    @Override
    public List<ItemSku> findAllByIdIn(List<Integer> idList) {
        return itemSkuRepository.findAllByIdIn(idList);
    }

    @Override
    public List<ItemSku> findAllByItemIdIn(List<Integer> itemIdList) {
        return itemSkuRepository.findAllByItemIdIn(itemIdList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void decreaseStock(List<DecreaseStockInput> decreaseStockInputList){
        for(DecreaseStockInput decreaseStockInput : decreaseStockInputList){
            Optional<ItemInfo> itemInfoOptional = itemInfoRepository.findById(decreaseStockInput.getItemId());
            // 判断商品是否存在
            if(!itemInfoOptional.isPresent()){
                throw new ItemException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            Optional<ItemSku> itemSkuOptional = itemSkuRepository.findById(decreaseStockInput.getSkuId());
            // 判断Sku是否存在
            if(!itemSkuOptional.isPresent()){
                throw new ItemException(ResultEnum.SKU_NOT_EXIST);
            }

            ItemSku itemSku = itemSkuOptional.get();
            // 库存是否足够
            Integer result = itemSku.getStock() - decreaseStockInput.getQuantity();
            if(result < 0){
                throw new ItemException(ResultEnum.PRODUCT_STOCK_ERROR);
            }

            itemSku.setStock(result);
            itemSkuRepository.save(itemSku);
        }
    }
}
